<template>
    <view class="zaiui-specs-page">
        <!--标题栏-->
        <bar-title bgColor='bg-white'>
            <block slot="content">填写规格</block>
        </bar-title>

        <scroll-view class="zaiui-scroll-view" scroll-y>
            <!--商品描述展示-->
            <view class="zaiui-section bg-white">
                <view class="zaiui-section-title">商品描述</view>
                <view class="zaiui-desc-content">
                    <view class="zaiui-desc-text">{{ productData.description }}</view>
                    <view class="zaiui-price-info">
                        <text class="current-price">¥{{ productData.price }}</text>
                        <text class="original-price" v-if="productData.originalPrice">原价 ¥{{ productData.originalPrice
                            }}</text>
                    </view>
                    <view class="zaiui-images-preview" v-if="productData.images.length > 0">
                        <scroll-view class="image-scroll" scroll-x>
                            <view class="image-list">
                                <image class="preview-image" v-for="(img, index) in productData.images" :key="index"
                                    :src="img" mode="aspectFill" />
                            </view>
                        </scroll-view>
                    </view>
                </view>
            </view>

            <!--规格参数-->
            <view class="zaiui-section bg-white">
                <view class="zaiui-section-title">规格参数</view>
                <view class="zaiui-specs-list">
                    <view class="zaiui-spec-item" v-for="(spec, index) in specs" :key="index">
                        <input class="spec-key-input" v-model="spec.label" placeholder="规格名称" />
                        <text class="spec-separator">:</text>
                        <input class="spec-value-input" v-model="spec.value"
                            :placeholder="spec.placeholder || '请输入规格值'" />
                        <text class="cuIcon-close delete-spec" @tap="deleteSpec(index)"/>
                    </view>
                </view>

                <!--直接添加一行规格-->
                <view class="zaiui-add-spec" @tap="addCustomSpec">
                    <text class="cuIcon-add margin-right-xs" />
                    <text>添加规格</text>
                </view>
            </view>

            <!--交易方式-->
            <view class="zaiui-section bg-white">
                <view class="zaiui-section-title">交易方式</view>
                <view class="zaiui-trade-options">
                    <view class="trade-option" v-for="(option, index) in tradeOptions" :key="index"
                        @tap="selectTradeOption(index)" :class="{ 'selected': option.selected }">
                        <text class="cuIcon-check text-red" v-if="option.selected" />
                        <text class="cuIcon-round text-gray" v-else />
                        <text class="option-text">{{ option.name }}</text>
                    </view>
                </view>

                <!--交易方式详情-->
                <view class="zaiui-trade-details" v-if="selectedTradeOption >= 0">
                    <view class="detail-title">{{ tradeOptions[selectedTradeOption].name }}详情</view>
                    <textarea class="trade-detail-textarea" v-model="tradeDetails"
                        :placeholder="tradeOptions[selectedTradeOption].detailPlaceholder" maxlength="200"
                        auto-height="true" />
                </view>
            </view>
        </scroll-view>

        <!--底部操作栏-->
        <view class="zaiui-footer-bar">
            <view class="zaiui-footer-content">
                <button class="cu-btn bg-gray round" @tap="goBack">上一步</button>
                <button class="cu-btn bg-red round" @tap="submitSpecs" :disabled="!canSubmit">
                    发布商品
                </button>
            </view>
        </view>


    </view>
</template>

<script>
import barTitle from '@/components/basics/bar-title';
import goodsAPI from '@/api/goods';
import storage from '@/utils/storage';

export default {
    components: {
        barTitle
    },
    data() {
        return {
            productData: {},
            specs: [],
            tradeOptions: [
                { name: '当面交易', selected: true, detailPlaceholder: '请填写交易地点和时间' },
                { name: '物流快递', selected: false, detailPlaceholder: '请填写快递方式和费用' },
                { name: '上门自提', selected: false, detailPlaceholder: '请填写自提地点和时间' }
            ],
            tradeDetails: ''
        }
    },
    computed: {
        canSubmit() {
            return this.selectedTradeOption >= 0 && this.tradeDetails.trim().length > 0;
        },
        selectedTradeOption() {
            return this.tradeOptions.findIndex(option => option.selected);
        }
    },
    onLoad() {
        try {
            const publishData = storage.get('publishData');
            this.productData = publishData;
            this.initSpecs();
        } catch (e) {
            console.error('解析数据失败:', e);
        }
    },
    methods: {
        async initSpecs() {
            // 根据分类智能生成规格
            const baseSpecs = [
                { label: '商品状态', value: '9成新', placeholder: '请选择商品状态（如：9成新）' },
                { label: '购买时间', value: '', placeholder: '请填写购买时间' },
                { label: '保修情况', value: '', placeholder: '请填写保修情况' },
                { label: '配件情况', value: '', placeholder: '请填写配件情况' }
            ];
			const category = await this.$store.getters['category/getCurrentCategory'];
            // 根据分类添加特定规格
            if (category) {
                try {
					const categorySpecs = await goodsAPI.generateCategorySpecs(category);
                    this.specs = [...baseSpecs, ...categorySpecs];
                } catch (error) {
                    console.error('获取分类规格失败:', error);
                    this.specs = baseSpecs;
                }
            } else {
                this.specs = baseSpecs;
            }
        },

        selectTradeOption(index) {
            this.tradeOptions.forEach((option, i) => {
                option.selected = i === index;
            });
            this.tradeDetails = ''; // 重置交易详情
        },

        addCustomSpec() {
            this.specs.push({
                label: '',
                value: '',
                placeholder: '请输入规格值'
            });
        },

        deleteSpec(index) {
            this.specs.splice(index, 1);
        },

        goBack() {
            uni.navigateBack();
        },

        async submitSpecs() {
            if (!this.canSubmit) {
                uni.showToast({
                    title: '请完善交易方式信息',
                    icon: 'none'
                });
                return;
            }

            // 收集规格数据
            const specsData = {};
            this.specs.forEach(spec => {
                if (spec.value.trim()) {
                    specsData[spec.label] = spec.value;
                }
            });

            // 准备提交的数据
            const submitData = {
                ...this.productData,
                specs: specsData,
                tradeType: this.tradeOptions[this.selectedTradeOption].name,
                tradeDetails: this.tradeDetails
            };

            // 显示加载提示
            uni.showLoading({
                title: '发布中...'
            });

            try {
                // 调用提交商品API
                const result = await goodsAPI.submitGoods(submitData);
                
                uni.hideLoading();
                uni.showToast({
                    title: '商品发布成功！',
                    icon: 'success'
                });

                // 跳转到商品详情页
                setTimeout(() => {
                    uni.redirectTo({
                        url: '/pages/goods/detail?id=' + (result.data ? result.data.id : Date.now())
                    });
                }, 1500);
            } catch (error) {
                uni.hideLoading();
                uni.showToast({
                    title: '发布失败，请重试',
                    icon: 'none'
                });
                console.error('提交商品失败:', error);
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.zaiui-specs-page {
    min-height: 100vh;
    background: #FAFAFA;

    .zaiui-scroll-view {
        height: calc(100vh - 100rpx - env(safe-area-inset-bottom));
        padding-bottom: 120rpx;
    }

    .zaiui-section {
        margin: 20rpx;
        border-radius: 16rpx;
        padding: 30rpx;
        background: white;

        .zaiui-section-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 30rpx;
            border-left: 6rpx solid #e54d42;
            padding-left: 20rpx;
        }

        // 商品描述内容
        .zaiui-desc-content {
            .zaiui-desc-text {
                font-size: 28rpx;
                line-height: 1.6;
                color: #333;
                margin-bottom: 20rpx;
                padding: 16rpx;
                background: #f8f8f8;
                border-radius: 8rpx;
            }

            .zaiui-price-info {
                display: flex;
                align-items: center;
                gap: 20rpx;
                margin-bottom: 20rpx;
                padding: 16rpx;
                background: #f8f8f8;
                border-radius: 8rpx;

                .current-price {
                    font-size: 36rpx;
                    font-weight: bold;
                    color: #e54d42;
                }

                .original-price {
                    font-size: 24rpx;
                    color: #999;
                    text-decoration: line-through;
                }
            }

            .zaiui-images-preview {
                margin-top: 20rpx;

                .image-scroll {
                    white-space: nowrap;
                }

                .image-list {
                    display: inline-flex;
                    gap: 12rpx;
                }

                .preview-image {
                    width: 120rpx;
                    height: 120rpx;
                    border-radius: 8rpx;
                    border: 1rpx solid #eee;
                }
            }
        }

        // 规格参数列表
        .zaiui-specs-list {
            margin-top: 20rpx;

            .zaiui-spec-item {
                display: flex;
                align-items: center;
                padding: 24rpx 0;
                border-bottom: 1rpx solid #f0f0f0;
                position: relative;

                &:last-child {
                    border-bottom: none;
                }

                .spec-key-input {
                    flex: 1;
                    font-size: 28rpx;
                    padding: 20rpx;
                    height: 80rpx;
                    background: #f8f8f8;
                    border-radius: 12rpx;
                    border: 2rpx solid #e8e8e8;
                    margin-right: 16rpx;
                    transition: all 0.3s ease;

                    &:focus {
                        border-color: #e54d42;
                        background: white;
                        box-shadow: 0 0 0 4rpx rgba(229, 77, 66, 0.1);
                    }
                }

                .spec-separator {
                    font-size: 28rpx;
                    color: #666;
                    margin: 0 16rpx;
                    font-weight: 600;
                }

                .spec-value-input {
                    flex: 2;
                    font-size: 28rpx;
                    padding: 20rpx;
                    height: 80rpx;
                    background: #f8f8f8;
                    border-radius: 12rpx;
                    border: 2rpx solid #e8e8e8;
                    margin-right: 16rpx;
                    transition: all 0.3s ease;

                    &:focus {
                        border-color: #e54d42;
                        background: white;
                        box-shadow: 0 0 0 4rpx rgba(229, 77, 66, 0.1);
                    }
                }

                .delete-spec {
                    font-size: 32rpx;
                    color: #e54d42;
                    padding: 16rpx;
                    border-radius: 8rpx;
                    background: rgba(229, 77, 66, 0.1);
                    transition: all 0.3s ease;

                    &:active {
                        background: rgba(229, 77, 66, 0.2);
                        transform: scale(0.95);
                    }
                }
            }
        }

        .zaiui-add-spec {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24rpx;
            margin-top: 24rpx;
            background: #f8f8f8;
            border-radius: 8rpx;
            border: 2rpx dashed #ddd;
            color: #666;
            font-size: 28rpx;
            font-weight: 500;
            transition: all 0.3s ease;

            &:active {
                background: #e8e8e8;
                transform: scale(0.98);
            }

            .cuIcon-add {
                color: #e54d42;
                font-size: 32rpx;
                margin-right: 12rpx;
            }
        }

        // 交易选项
        .zaiui-trade-options {
            .trade-option {
                display: flex;
                align-items: center;
                padding: 20rpx;
                margin-bottom: 16rpx;
                background: #f8f8f8;
                border-radius: 8rpx;
                border: 1rpx solid transparent;
                transition: all 0.3s ease;

                &.selected {
                    background: #fff1f0;
                    border-color: #e54d42;
                }

                .cuIcon-check {
                    color: #e54d42;
                    font-size: 28rpx;
                }

                .cuIcon-round {
                    color: #bdbdbd;
                    font-size: 28rpx;
                }

                .option-text {
                    font-size: 28rpx;
                    color: #333;
                    margin-left: 16rpx;
                    font-weight: 500;
                }
            }
        }

        // 交易详情
        .zaiui-trade-details {
            margin-top: 24rpx;
            padding: 24rpx;
            background: #f8f8f8;
            border-radius: 12rpx;

            .detail-title {
                font-size: 28rpx;
                color: #333;
                font-weight: 500;
                margin-bottom: 16rpx;
            }

            .trade-detail-textarea {
                width: 100%;
                min-height: 160rpx;
                padding: 20rpx;
                background: white;
                border-radius: 12rpx;
                border: 2rpx solid #e8e8e8;
                font-size: 28rpx;
                line-height: 1.5;
                transition: all 0.3s ease;

                &:focus {
                    border-color: #e54d42;
                    background: white;
                    box-shadow: 0 0 0 4rpx rgba(229, 77, 66, 0.1);
                }
            }
        }
    }

    .zaiui-footer-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        padding: 20rpx;
        padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
        border-top: 1rpx solid #eee;

        .zaiui-footer-content {
            display: flex;
            justify-content: space-between;
            gap: 20rpx;

            .cu-btn {
                flex: 1;
                height: 80rpx;
                font-size: 32rpx;

                &:disabled {
                    background: #ccc !important;
                    color: #999 !important;
                }
            }
        }
    }
}
</style>